<template>
  <div class="upload-file">
    <el-upload
      ref="upload"
      :auto-upload="true"
      :http-request="handleUpload"
      action=""
      :disabled="disabled"
      :before-upload="handleBeforeUpload"
      :on-success="handleFileSuccess"
      :on-error="handleUploadError"
      :file-list="fileList"
      :show-file-list="false"
      class="upload-file-uploader"
    >
      <!-- 上传按钮 -->
      <div class="upload-btn" v-if="!fileList || fileList.length === 0">
        <i class="el-icon-plus"></i>
        <span class="words">点击上传</span>
      </div>
      <div class="file-box" v-else>
        <span class="file-name">{{ fileName }}</span>
        <span class="change-btn">更换</span>
      </div>
      <!-- <el-button v-if="!fileList || fileList.length === 0" size="mini" type="primary">选取文件</el-button> -->
      <!-- 上传提示 -->
      <div v-if="showTip" slot="tip" class="el-upload__tip">
        请上传
        <template v-if="fileSize">
          <!--  style="color: #f56c6c" -->
          大小不超过 <b>{{ fileSize }}MB</b>
        </template>
        <template v-if="fileType">
          <!-- style="color: #f56c6c" -->
          格式为 <b>{{ fileType.join("/") }}</b>
        </template>
        的文件
      </div>
    </el-upload>
  </div>
</template>

<script>
import OSS from 'ali-oss'
import { getOssInfo } from '@/request/api'
export default {
  name: "PdfUpload",
  model: {
    prop: 'value',
    event: 'input'
  },
  props: {
    // 值
    // eslint-disable-next-line vue/require-default-prop
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 1,
    },
    isShowVideoTips: {
      type: Boolean,
      default: true,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 1.5,
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
    fileType: {
      type: Array,
      default: ["zip"],
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      fileList: [],
      fileUrl: "",
      fileName: "",
      oss: null
    };
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          let temp = 1;
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(",");
          // 然后将数组转为对象数组
          this.fileList = list.map((item) => {
            if (typeof item === "string") {
              item = { name: item, url: item };
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    this.initOSS()
  },
  methods: {
    async initOSS() {
      const res = await getOssInfo()
      if (res) {
        const { accessKey, accessSecret, bucket, endpoint } = res.data
        this.oss = new OSS({
          // 阿里云oss相关信息
          region: endpoint.split('.')[0],
          accessKeyId: accessKey,
          accessKeySecret: accessSecret,
          bucket: bucket
        })
      }
    },
    handleUpload(option) {
      const { file } = option
      const randomName = this.getFileNameUUID()
      const key = 'datarOSS/' + randomName + file.name // 设置上传路径
      const ossOptions = {
        headers: {
          'Content-Type': file.type,
          'Content-Disposition': 'inline'
        }
      }
      this.oss
        .put(key, file, ossOptions)
        .then((result) => {
          this.handleFileSuccess(result.url, file)
        })
        .catch((error) => {
          // 上传失败的操作
          this.handleUploadError()
        })
    },
    getFileNameUUID() {
      function rx() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
      }
      return `${+new Date()}_${rx()}${rx()}`
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      const fileTypeList = this.fileType.map((v) => {
        return v.slice(1);
      });
      let isAble = false;

      fileTypeList.forEach((v) => {
        if (file.type.indexOf(v) > -1) {
          isAble = true;
        }
      });
      console.log(fileTypeList, file.type, "----file---");
      if (!isAble) {
        this.$modal.msgError(`请上传${fileType.join("/")}文件`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传，请稍候...");
      this.number++;
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    // 上传成功回调
    handleFileSuccess(url, file) {
      console.log(url, file, "----上传结果");
      this.$refs.upload.clearFiles();
      this.$modal.closeLoading();
        this.uploadList.push({ name: file.name, url:url });
        if (this.uploadList.length === this.number) {
          this.fileList = this.fileList.concat(this.uploadList);
          this.getFiles(url, file);
          this.uploadList = [];
          this.number = 0;
          this.$emit(
            "input",
            this.listToString([{ name: file.name, url: url }])
          );
        }
    },
    getFiles(res, file) {
      this.fileName = file.name;
      this.fileUrl = res.data;
      console.log(this.fileName, "----this.fileName");
      console.log(this.fileUrl, "----this.fileUrl");
    },
    // 删除文件
    handleDelete(index) {
      this.fileList.splice(index, 1);
      this.$emit("input", this.listToString(this.fileList));
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return "";
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (const i in list) {
        strs += list[i].url + separator;
      }
      return strs != "" ? strs.substr(0, strs.length - 1) : "";
    },
  },
};
</script>

<style scoped lang="less">
.upload-file-uploader {
  margin-bottom: 5px;

  .el-upload-list {
    display: none;
  }

  .upload-btn {
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .el-icon-plus {
      font-size: 15px;
      color: #3d6cb0;
      margin-right: 5px;
    }
    .words {
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #3d6cb0;
      line-height: 22px;
    }
  }

  .file-box {
    .file-name {
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #37383d;
      margin-right: 15px;
    }
    .change-btn {
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #3d6cb0;
    }
  }
}
.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
